package com.pan.service.aspect;

import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ServiceException;
import com.pan.tools.ArrayTools;
import com.pan.tools.RedisTools;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Aspect
public class OperationCouponAspect{

    @Resource
    private RedisTools redisTools;

    @Pointcut("execution(public com.pan.entity.Result com.pan.service.impl.OperationCouponServiceImpl.setSeckillCoupon(java.lang.String,java.lang.Long,java.util.Date))")
    public void setSeckillCouponCut(){}

    @Before("setSeckillCouponCut()")
    public void checkAdminLogin(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames =  methodSignature.getParameterNames();
        Integer index = ArrayTools.indexOf(parameterNames,"adminTicket");
        if (index == null){
            throw new ServiceException(ErrorCode.ASPECT_ERROR);
        }
        String adminTicket = (String) args[index];
        boolean isAdmin = redisTools.exists("admin:"+adminTicket).getData();
        if (!isAdmin){
            throw new ServiceException(ErrorCode.NOT_LOGIN);
        }
    }

}
